<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" placeholder="请输入搜索内容">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="users" height="360" border style="width: 100%" stripe>
        <el-table-column width="60" type="index"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" width="100%">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#1E90FF"
              inactive-color="#B0C4DE"
              @change="userstate(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260%">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="bzUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-s-custom"
                circle
                @click="setjs(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="del(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="pagesizes"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tol"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户提示框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      @close="DialogClosed"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="subUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户提示框 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="bzdialogVisible"
      width="50%"
      @close="DialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bzdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setDialogVisible"
      width="50%"
      @close="selDialogClosed"
    >
      <el-form labelPosition="right" label-width="180px" :model="uinfo"  ref="ruleForm">
        <el-form-item label="当前用户：">
          <el-input v-model="uinfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前角色：">
          <el-input v-model="uinfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="更改角色">
          <el-select v-model="selectRoles" placeholder="请选择角色">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subjs">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    var checkMob = (rule, value, callback) => {
      const regMob = /^1[3|4|5|7|8][0-9]{9}$/;
      if (regMob.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的电话号码"));
    };
    return {
      users: [],
      tol: 0,
      pagesizes: [ 4, 6, 8],
      queryInfo: {
        query: null,
        pagenum: 1,
        pagesize: 4,
      },
      dialogFormVisible: false,
      bzdialogVisible: false,
      setDialogVisible: false,
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3~10 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6~15 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMob, trigger: "blur" },
        ],
      },
      editForm: {},
      uinfo: {}, //分配角色的信息
      rolesList: [], //所有角色的数据列表
      selectRoles: '', //已选中的角色
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200)
        return this.$message.error("获取用户列表失败");
      this.users = res.data.users;
      this.tol = res.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUsers();
    },
    async userstate(info) {
      const { data: re } = await this.$http.put(
        "users/" + parseInt(info.id) + "/state/" + info.mg_state
      );
      if (re.meta.status !== 200) {
        info.mg_state = !info.mg_state;
        return this.$message.error("更改失败");
      }
      this.$message.success("更改成功");
    },
    //添加
    addUser() {
      this.dialogFormVisible = true;
    },
    //点击关闭时重置输入框
    DialogClosed() {
      this.$refs.ruleForm.resetFields();
    },
    selDialogClosed(){
      this.selectRoles = '';
      this.uinfo = {}
    },
    //先预验证再请求数据库判断
    subUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: re } = await this.$http.post("users", this.ruleForm);
        console.log(re)
        if (re.meta.status !== 201) {
          if(re.meta.status === 400){
            return this.$message.error("添加失败，用户名已存在");
          }
          this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.dialogFormVisible = false;
        this.getUsers();
      });
    },
    //编辑
    async bzUser(id) {
      this.bzdialogVisible = true;
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
    },
    editUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: re } = await this.$http.put("users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        if (re.meta.status !== 200) {
          return this.$message.error("编辑失败");
        }
        this.$message.success("编辑成功");
        this.bzdialogVisible = false;
        this.getUsers();
      });
    },
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.getUsers();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    setjs(info) {
      this.uinfo = info;
      this.getRoles();
      this.setDialogVisible = true;
    },
    async getRoles() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限用户失败");
      }
      this.rolesList = res.data;
      console.log(res.data);
    },
    async subjs(){
      if(!this.selectRoles){
        return this.$message.error('请选择要更改的角色')
      }
      const { data:res } = await this.$http.put(`users/${this.uinfo.id}/role`,{
        id:this.uinfo.id,
        rid:this.selectRoles
      })
      if (res.meta.status !== 200) {
        return this.$message.error("分配用户角色失败");
      }
      this.$message.success("分配用户角色成功");
      this.setDialogVisible = false;
      this.getUsers();
    }
  },
};
</script>
<style>
.el-breadcrumb {
  margin-bottom: 30px;
}
.el-row {
  margin-bottom: 20px;
}
</style>